<template>
  <div class="login-container">
    <!-- 导航栏 -->
    <van-nav-bar class="page-nav-bar" title="登录">
      <template #left>
        <!-- 后退上一页:  $router.back() 或 $router.go(-1) -->
        <van-icon name="cross" @click="$router.back()" />
      </template>
    </van-nav-bar>
    <!-- 表单 -->
    <van-form @submit="onSubmit" ref="loginForm">
      <!-- 手机号框 -->
      <van-field name="mobile" placeholder="请输入手机号" v-model="user.mobile" :rules="userFormRules.mobile" type="number" maxlength="11">
        <template #left-icon>
          <i class="toutiao toutiao-shouji"></i>
        </template>
      </van-field>
      <!-- 验证码框 -->
      <van-field name="code" placeholder="请输入验证码" v-model="user.code" :rules="userFormRules.code" type="number" maxlength="6">
        <template #left-icon>
          <i class="toutiao toutiao-yanzhengma"></i>
        </template>
        <!-- 发送验证码按钮 -->
        <template #button>
          <!-- 通过变量控制倒计时显示 , @finish 为倒计时结束触发的事件 -->
          <van-count-down :time="time" format="ss s" v-if="isCountDownShow" @finish="isCountDownShow = false"/>
          <!--  native-type="button" 表单不默认提交  -->
          <van-button v-else class="send-btn" round size="small"  native-type="button" type="default" @click="onSendSms">
              发送验证码
           </van-button>
        </template>
      </van-field>
      <!-- 登录按钮 -->
      <div class="login-btn-wrap">
        <van-button class="login-btn" block type="info" native-type="submit">登录</van-button>
      </div>
    </van-form>
  </div>
</template>

<script>
import { login, sendSms } from '@/api/user'
export default {
  name: 'LoginIndex',
  components: {},
  props: {},
  data () {
    return {
      user: {
        mobile: '',
        code: ''
      },
      userFormRules: {
        mobile: [
          {
            required: true,
            message: '手机号不能为空'
          },
          {
            pattern: /^1[3|5|6|7|8]\d{9}$/,
            message: '手机号格式错误!'
          }
        ],
        code: [
          {
            required: true,
            message: '验证码不能为空'
          },
          {
            pattern: /^\d{6}$/,
            message: '验证码格式错误!'
          }
        ]
      },
      time: 60 * 1000,
      isCountDownShow: false
    }
  },
  computed: {},
  watch: {},
  created () {},
  mounted () {},
  methods: {
    async onSubmit (values) {
      //  获取表单数据
      const user = this.user
      //  验证表单数据
      //  发送网络请求
      this.$toast.loading({
        message: '登录中...',
        forbidClick: true, //  是否禁止背景点击
        duration: 0 //  0 表示永久持续下去,可设置持续的事件
      })
      //  发送请求,实现登录
      try {
        const res = await login(user)
        console.log('请求成功', res)
        this.$toast.success('登录成功！')
        this.$router.push('/')
        //  将用户数据存储到vuex中
        this.$store.commit('setUser', res.data)
      } catch (error) {
        if (error.response.status === 400) {
          console.log('手机号或验证码错误!')
          this.$toast.fail('手机号或验证码错误！')
        } else {
          console.log('未知的错误')
          this.$toast.fail('登录失败，请稍后重试！')
        }
      }
    },
    async onSendSms () {
      //  验证手机号是否正确
      try {
        await this.$refs.loginForm.validate('mobile')
      } catch (error) {
        return console.log('手机号验证失败')
      }
      //  验证通过,显示倒计时
      this.isCountDownShow = true
      //  发送验证码
      try {
        await sendSms(this.user.mobile)
        this.$toast('发送成功')
      } catch (error) {
        this.isCountDownShow = false
        // 同手机号每分钟只能请求一次,否则报错429
        if (error.response.status === 429) {
          this.$toast('发送太频繁,请稍后再试')
        } else {
          this.$toast('发送失败,请稍后再试')
        }
      }
    }
  }
}
</script>

<style scoped lang="less">
.login-container {
  .toutiao {
    font-size: 37px;
  }
  .send-btn {
    height: 46px;
    line-height: 46px;
    background-color: #ededed;
    font-size: 22px;
    color: #666;
  }
  .login-btn-wrap {
    padding: 53px 33px;
    .login-btn {
      background-color: #6db4fb;
      border: none;
    }
  }
}

</style>
